var api = require('../../../config/api.js');
var util = require('../../../utils/util.js');
var check = require('../../../utils/check.js');
var user = require('../../../utils/user.js');

var app = getApp();
Page({
  data: {
    userInfo: {
      nickName: '点击登录',
      avatarUrl: '/static/images/my.png'
    },
    userApproveInfo: {
      contactName: '',
      contactTel: '',
      contactAddress: '',
      userType: 0,
      companyName: '',
      companyLogo: '',
      adminUsername: '',
      herbInfoList: [],
    },
    hasLogin: false,
    username: '',
    password: '',
    confirmPassword: '',
    mobile: '',
    code: '',

    contactName: '',
    contactTel: '',
    contactAddress: '',
    userTypes: [{
        value: '0',
        name: '个人认证',
        checked: true
      },
      {
        value: '1',
        name: '车行'
      },
      {
        value: '2',
        name: '医药公司'
      },
    ],
    userType: '0',
    companyName: '',
    //新组件上传实现
    //logo上传
    logoFileList: [],
    //身份证正面上传
    idCard1FileList: [],
    //身份证背面上传
    idCard2FileList: [],
    //营业执照上传
    certificatesFileList: [],
    herbList: [],
    selectHerbsInfo: '',
    localHerbList: [],
    localSelectHerbsInfo: '',
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    // 页面渲染完成
  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示
    //获取用户的登录信息
    if (app.globalData.hasLogin) {
      let userInfo = wx.getStorageSync('userInfo');
      this.setData({
        userInfo: userInfo,
        hasLogin: true
      });
      this.getQualificationsDetail();
    }
  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  callbackSetSelectHerbList(selectHerbs, selectHerbsInfo) {
    this.setData({
      herbList: selectHerbs,
      selectHerbsInfo: selectHerbsInfo
    })
  },
  getQualificationsDetail() {
    wx.showLoading({
      title: '加载中',
    });
    setTimeout(function () {
      wx.hideLoading()
    }, 2000);

    let that = this;
    util.request(api.QualificationsDetail, {
      isAuth: 1
    }).then(function (res) {
      if (res.errno === 0) {
        let userApproveInfo = res.data.userApproveInfo;
        let userType = userApproveInfo.userType + '';
        that.setData({
          userApproveInfo: userApproveInfo,
          userType: userType
        });
        if (userApproveInfo.contactName) {
          that.setData({
            contactName: userApproveInfo.contactName
          });
        }
        if (userApproveInfo.contactTel) {
          that.setData({
            contactTel: userApproveInfo.contactTel
          });
        }
        if (userApproveInfo.contactAddress) {
          that.setData({
            contactAddress: userApproveInfo.contactAddress
          });
        }
        if (userType) {
          that.onUserTypeSelect(userType);
        }
        if (userType == '0') {
          let herbInfoList = that.data.userApproveInfo.herbInfoList;
          if (herbInfoList && herbInfoList.length > 0) {
            let herbGenericNameList = herbInfoList.map((t) => t.genericName);
            that.setData({
              localHerbList: herbInfoList,
              localSelectHerbsInfo: herbGenericNameList.join(',')
            });
          }
        } else {
          if (userApproveInfo.adminUsername) {
            that.setData({
              username: userApproveInfo.adminUsername
            });
          }

          if (userApproveInfo.companyName) {
            that.setData({
              companyName: userApproveInfo.companyName
            });
          }
          let companyLogoStr = that.data.userApproveInfo.companyLogo;
          if (companyLogoStr != null && companyLogoStr != '') {
            that.setData({
              logoFileList: companyLogoStr.split(',').map((t) => {
                return {
                  url: t
                };
              })
            });
          }
          let certificatesImageStr = that.data.userApproveInfo.certificatesImage;
          if (certificatesImageStr != null && certificatesImageStr != '') {
            that.setData({
              certificatesFileList: certificatesImageStr.split(',').map((t) => {
                return {
                  url: t
                };
              })
            });
          }
        }
      }
      let idCard1UrlStr = that.data.userApproveInfo.idCard1Url;
      if (idCard1UrlStr != null && idCard1UrlStr != '') {
        that.setData({
          idCard1FileList: idCard1UrlStr.split(',').map((t) => {
            return {
              url: t
            };
          })
        });
      }
      let idCard2UrlStr = that.data.userApproveInfo.idCard2Url;
      if (idCard2UrlStr != null && idCard2UrlStr != '') {
        that.setData({
          idCard2FileList: idCard2UrlStr.split(',').map((t) => {
            return {
              url: t
            };
          })
        });
      }
      wx.hideLoading();
    });
  },
  sendCode: function () {
    let that = this;

    if (this.data.mobile.length == 0) {
      wx.showModal({
        title: '错误信息',
        content: '手机号不能为空',
        showCancel: false
      });
      return false;
    }

    wx.request({
      url: api.AuthRegisterCaptcha,
      data: {
        mobile: that.data.mobile
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.errno == 0) {
          wx.showModal({
            title: '发送成功',
            content: '验证码已发送',
            showCancel: false
          });
        } else {
          wx.showModal({
            title: '错误信息',
            content: res.data.errmsg,
            showCancel: false
          });
        }
      }
    });
  },
  requestApplyAuth: function (wxCode) {
    let that = this;

    //上传商户图标Logo
    let logoFileUrlList = [];
    if (this.data.logoFileList) {
      logoFileUrlList = this.data.logoFileList.map((t) => t.url)
    }
    //上传身份证正面
    let idCard1FileUrlList = [];
    if (this.data.idCard1FileList) {
      idCard1FileUrlList = this.data.idCard1FileList.map((t) => t.url)
    }
    //上传身份证背面
    let idCard2FileUrlList = [];
    if (this.data.idCard2FileList) {
      idCard2FileUrlList = this.data.idCard2FileList.map((t) => t.url)
    }
    //上传营业执照
    let certificatesFileUrlList = [];
    if (this.data.certificatesFileList) {
      certificatesFileUrlList = this.data.certificatesFileList.map((t) => t.url)
    }
    let herbList = this.data.herbList.length > 0 ? this.data.herbList : this.data.localHerbList;

    wx.request({
      url: api.AuthApplyAuth,
      data: {
        username: that.data.username,
        password: that.data.password,
        mobile: that.data.mobile,
        code: that.data.code,
        contactName: that.data.contactName,
        contactTel: that.data.contactTel,
        contactAddress: that.data.contactAddress,
        userType: that.data.userType,
        companyName: that.data.companyName,
        logoFileUrlList: logoFileUrlList,
        herbList: herbList.map((t) => t.genericName),
        // herbList:that.data.herbList,
        idCard1FileUrlList: idCard1FileUrlList,
        idCard2FileUrlList: idCard2FileUrlList,
        certificatesFileUrlList: certificatesFileUrlList,
        wxCode: wxCode
      },
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'X-Litemall-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.errno == 0) {
          app.globalData.hasLogin = true;
          // wx.setStorageSync('userInfo', res.data.data.userInfo);
          // wx.switchTab({
          //   url: '/pages/ucenter/index/index'
          // });
          // wx.navigateTo({
          //   url: "/pages/ucenter/qualifications/qualifications?status=1"
          // });
          user.ApproveRequestSubscribeMessage(function () {
            that.checkShopInfo();
          });
        } else {
          wx.showModal({
            title: '错误信息',
            content: res.data.errmsg,
            showCancel: false
          });
        }
      }
    });
  },
  /**
   * 用户认证信息检查{未认证用户：跳转到商户认证等待界面，已认证用户跳转到资质页面}
   */
  checkShopInfo: function () {
    let shopInfo = wx.getStorageSync('shopInfo');
    if (shopInfo) {
      wx.switchTab({
        url: '/pages/ucenter/index/index'
      });
      wx.navigateTo({
        url: "/pages/ucenter/qualifications/qualifications?status=1"
      });
    } else {
      wx.reLaunch({
        url: "/pages/auth/authenticationIdentityWait/authenticationIdentityWait"
      });
    }
  },
  onUserTypeChange: function (e) {
    this.onUserTypeSelect(e.detail.value);
  },
  onUserTypeSelect: function (userType) {
    const userTypes = this.data.userTypes
    for (let i = 0, len = userTypes.length; i < len; ++i) {
      userTypes[i].checked = userTypes[i].value === userType
    }
    this.setData({
      userTypes,
      userType: userType
    })
  },
  //添加herb
  addHerb: function () {
    let that = this;
    if (app.globalData.hasLogin) {
      let herbList = that.data.herbList.length > 0 ? that.data.herbList : that.data.localHerbList;
      wx.setStorageSync('auth_selectHerbList', herbList);
      wx.navigateTo({
        url: "/pages/auth/herb/herb"
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  startAuthCheck: function (callback) {
    if (app.globalData.hasLogin) {
      util.request(api.CouuntTargetStatus, {
        status: 0
      }).then(function (res) {
        if (res.errno === 0) {
          if (res.data > 0) {
            wx.showModal({
              title: '错误信息',
              content: '存在未审核的认证信息',
              showCancel: false
            });
            return false;
          } else {
            callback();
          }
        }
      })
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  startAuthConfirm() {
    user.tokenCheck(this.startAuthConfirmCallback);
  },
  startAuthConfirmCallback() {
    // console.log(this.data.herbList)
    let that = this;
    wx.showModal({
      title: '',
      confirmColor: '#b4282d',
      content: '您确定要提交吗？',
      success: function (res) {
        if (!res.confirm) {
          return;
        }
        that.startAuth();
      }
    })
  },
  startAuth: function () {
    var that = this;
    let herbList = this.data.herbList.length > 0 ? this.data.herbList : this.data.localHerbList;

    if (this.data.contactName.length == 0 ||
      this.data.contactTel.length == 0 ||
      this.data.contactAddress.length == 0) {
      wx.showModal({
        title: '错误信息',
        content: '联系人、电话、地址不能为空',
        showCancel: false
      });
      return false;
    }
    if (!check.isValidPhone(this.data.contactTel)) {
      wx.showModal({
        title: '错误信息',
        content: '联系电话格式不正确',
        showCancel: false
      });
      return false;
    }

    if ('0' == this.data.userType) {
      if (herbList.length == 0) {
        wx.showModal({
          title: '错误信息',
          content: '请选择药品品类',
          showCancel: false
        });
        return false;
      }

      if (this.data.idCard1FileList.length == 0) {
        wx.showModal({
          title: '错误信息',
          content: '请选上传身份证正面图片',
          showCancel: false
        });
        return false;
      }
      if (this.data.idCard2FileList.length == 0) {
        wx.showModal({
          title: '错误信息',
          content: '请选上传身份证背面图片',
          showCancel: false
        });
        return false;
      }
    } else if (['1', '2'].includes(this.data.userType)) {
      if (this.data.companyName.length == 0) {
        wx.showModal({
          title: '错误信息',
          content: '商户名称不能为空',
          showCancel: false
        });
        return false;
      }
      if (this.data.logoFileList.length == 0) {
        wx.showModal({
          title: '错误信息',
          content: '请选上传商户logo图片',
          showCancel: false
        });
        return false;
      }
      if (this.data.password.length < 6 || this.data.username.length < 6) {
        wx.showModal({
          title: '错误信息',
          content: '登录账号和密码不得少于6位',
          showCancel: false
        });
        return false;
      }

      if (this.data.password != this.data.confirmPassword) {
        wx.showModal({
          title: '错误信息',
          content: '确认密码不一致',
          showCancel: false
        });
        return false;
      }

      if (this.data.idCard1FileList.length == 0) {
        wx.showModal({
          title: '错误信息',
          content: '请选上传身份证正面图片',
          showCancel: false
        });
        return false;
      }
      if (this.data.idCard2FileList.length == 0) {
        wx.showModal({
          title: '错误信息',
          content: '请选上传身份证背面图片',
          showCancel: false
        });
        return false;
      }
      if (this.data.certificatesFileList.length == 0) {
        wx.showModal({
          title: '错误信息',
          content: '请选上传营业执照图片',
          showCancel: false
        });
        return false;
      }
    }

    that.requestApplyAuth('')
    // wx.login({
    //   success: function (res) {
    //     if (!res.code) {
    //       wx.showModal({
    //         title: '错误信息',
    //         content: '商户认证失败',
    //         showCancel: false
    //       });
    //     }
    //   }
    // });
  },
  bindUsernameInput: function (e) {

    this.setData({
      username: e.detail.value
    });
  },
  bindPasswordInput: function (e) {

    this.setData({
      password: e.detail.value
    });
  },
  bindConfirmPasswordInput: function (e) {

    this.setData({
      confirmPassword: e.detail.value
    });
  },
  bindMobileInput: function (e) {

    this.setData({
      mobile: e.detail.value
    });
  },
  bindCodeInput: function (e) {

    this.setData({
      code: e.detail.value
    });
  },
  bindContactNameInput: function (e) {
    this.setData({
      contactName: e.detail.value
    });
  },
  bindContactTelInput: function (e) {
    this.setData({
      contactTel: e.detail.value
    });
  },
  bindContactAddressInput: function (e) {
    this.setData({
      contactAddress: e.detail.value
    });
  },
  bindCompanyNameInput: function (e) {
    this.setData({
      companyName: e.detail.value
    });
  },
  clearInput: function (e) {
    switch (e.currentTarget.id) {
      case 'clear-username':
        this.setData({
          username: ''
        });
        break;
      case 'clear-password':
        this.setData({
          password: ''
        });
        break;
      case 'clear-confirm-password':
        this.setData({
          confirmPassword: ''
        });
        break;
      case 'clear-mobile':
        this.setData({
          mobile: ''
        });
        break;
      case 'clear-code':
        this.setData({
          code: ''
        });
        break;
      case 'clear-contact_name':
        this.setData({
          contactName: ''
        });
        break;
      case 'clear-contact_tel':
        this.setData({
          contactTel: ''
        });
        break;
      case 'clear-contact_address':
        this.setData({
          contactAddress: ''
        });
        break;
      case 'clear-company_name':
        this.setData({
          companyName: ''
        });
        break;
    }
  },
  //图片上传
  //logo 上传
  logoAfterRead(event) {
    let that = this;
    const {
      file
    } = event.detail;
    wx.showLoading({
      title: '上传中...',
      mask: true
    });
    util.upload(file, function (_res) {
      // 上传完成需要更新 fileList
      let url = _res.data.url
      const {
        logoFileList = []
      } = that.data;
      logoFileList.push({
        ...file,
        url: url
      });
      that.setData({
        logoFileList
      });
    }, function () {
      wx.hideLoading();
    })
  },
  //身份证正面 上传
  idCard1BeforeRead(event) {
    const {
      file,
      callback
    } = event.detail;
    callback(file.type === 'image');
  },
  idCard1AfterRead(event) {
    let that = this;
    const {
      file
    } = event.detail;
    wx.showLoading({
      title: '上传中...',
      mask: true
    });
    util.upload(file, function (_res) {
      // 上传完成需要更新 fileList
      let url = _res.data.url
      const {
        idCard1FileList = []
      } = that.data;
      idCard1FileList.push({
        ...file,
        url: url
      });
      that.setData({
        idCard1FileList
      });
    }, function () {
      wx.hideLoading();
    });
  },
  //身份证背面 上传
  idCard2AfterRead(event) {
    let that = this;
    const {
      file
    } = event.detail;
    wx.showLoading({
      title: '上传中...',
      mask: true
    });
    util.upload(file, function (_res) {
      // 上传完成需要更新 fileList
      let url = _res.data.url
      const {
        idCard2FileList = []
      } = that.data;
      idCard2FileList.push({
        ...file,
        url: url
      });
      that.setData({
        idCard2FileList
      });
    }, function () {
      wx.hideLoading();
    })
  },
  //营业执照 上传
  certificatesAfterRead(event) {
    let that = this;
    const {
      file
    } = event.detail;
    wx.showLoading({
      title: '上传中...',
      mask: true
    });
    util.upload(file, function (_res) {
      // 上传完成需要更新 fileList
      let url = _res.data.url
      const {
        certificatesFileList = []
      } = that.data;
      certificatesFileList.push({
        ...file,
        url: url
      });
      that.setData({
        certificatesFileList
      });
    }, function () {
      wx.hideLoading();
    })
  },
  logoDelete(event) {
    const {
      index
    } = event.detail;
    let logoFileList = this.data.logoFileList;
    logoFileList.splice(index, 1)
    this.setData({
      logoFileList
    });
  },
  idCard1Delete(event) {
    const {
      index
    } = event.detail;
    let idCard1FileList = this.data.idCard1FileList;
    idCard1FileList.splice(index, 1)
    this.setData({
      idCard1FileList
    });
  },
  idCard2Delete(event) {
    const {
      index
    } = event.detail;
    let idCard2FileList = this.data.idCard2FileList;
    idCard2FileList.splice(index, 1)
    this.setData({
      idCard2FileList
    });
  },
  certificatesDelete(event) {
    const {
      index
    } = event.detail;
    let certificatesFileList = this.data.certificatesFileList;
    certificatesFileList.splice(index, 1)
    this.setData({
      certificatesFileList
    });
  },
})